package net.sk.china.platform.utils;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import net.sk.china.common.exception.TalkException;
import net.sk.china.common.utils.JwtUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;

/**
 * 国密 SM4 加解密
 * +----------------------------------------------------------------------
 * | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2018-2024 聊来All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * +----------------------------------------------------------------------
 * | @Author: 聊来 <18970881148@qq.com>
 * +----------------------------------------------------------------------
 * | DateTime: 2024/6/2 14:49
 * +----------------------------------------------------------------------
 */
public class Sm4Util {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    private static final String ENCODING = "UTF-8";
    private static final String ALGORITHM_NAME = "SM4";
    /** 加密算法/分组加密模式/分组填充方式、PKCS5Padding-以 8 个字节为一组分组加密、定义分组加密模式使用：PKCS5Padding */
    private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    /** 128-32 位 16 进制;256-64 位 16 进制 */
    private static final int DEFAULT_KEY_SIZE = 128;

    /**
     * 生成 ECB 暗号
     * @param algorithmName 算法名称
     * @param mode 模式
     * @param key key
     * @return {@code Cliper}
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName,
                BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }
    public static byte[] generateKey() throws Exception {
        return generateKey(DEFAULT_KEY_SIZE);
    }
    private static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME,
                BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }
    /**
     * sm4 加密
     * @param hexKey 16 进制秘钥（忽略大小写）
     * @param paramStr 待加密字符串
     * @return 返回 16 进制的加密字符串
     */
    public static String encryptEcb(String hexKey, String paramStr) throws Exception {
        String cipherText;

        // 16 进制字符串-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);

        // String-->byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);

        // 加密后的数组
        byte[] cipherArray = encryptEcbPadding(keyData, srcData);

        // byte[]-->hexString
        cipherText = ByteUtils.toHexString(cipherArray);

        return cipherText;
    }

    /**
     * 加密模式之 Ecb
     * @param key 加密key
     * @param data 加密数据
     * @return {@code byte[]}
     */
    private static byte[] encryptEcbPadding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);

        return cipher.doFinal(data);
    }

    /**
     * sm4 解密
     * @param hexKey 16 进制密钥
     * @param cipherText 16 进制的加密字符串（忽略大小写）
     * @return {@code String}
     */
    public static String decryptEcb(String hexKey, String cipherText) throws Exception {
        String decryptStr;
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);

        // hexString-->byte[]
        byte[] cipherData = ByteUtils.fromHexString(cipherText);

        // 解密
        byte[] srcData = decryptEcbPadding(keyData, cipherData);

        // byte[]-->String
        decryptStr = new String(srcData, ENCODING);

        return decryptStr;
    }

    /**
     * 解密模式之 Ecb
     * @param key 解密key
     * @param cipherText 解密数据
     * @return {@code byte[]}
     */
    private static byte[] decryptEcbPadding(byte[] key, byte[] cipherText) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);

        return cipher.doFinal(cipherText);
    }

    /**
     * 校验加密前后的字符串是否为同一数据
     * @param hexKey 16 进制密钥（忽略大小写）
     * @param cipherText 16 进制加密后的字符串
     * @param paramStr 加密前的字符串
     * @return {@code String}
     */
    public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception {
        // 用于接收校验结果
        boolean flag = false;

        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);

        // 将 16 进制字符串转换成数组
        byte[] cipherData = ByteUtils.fromHexString(cipherText);

        // 解密
        byte[] decryptData = decryptEcbPadding(keyData, cipherData);

        // 将原字符串转换成 byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);

        // 判断 2 个数组是否一致
        flag = Arrays.equals(decryptData, srcData);

        return flag;
    }

    /**
     * 验证数据
     * @param request 请求数据
     * @param tClass 解析后的数据
     * @param http 请求头
     * @param <T> 泛型数据
     * @param <tClass> 泛型数据
     */
    public static <T, tClass> void openCheckData(T request, Class<tClass> tClass, HttpServletRequest http) {
        String token = http.getHeader("token");
        Claims claims = JwtUtil.getInstance().checkToken(token);
        tClass checkData = JSONObject.parseObject(claims.get("data").toString(), tClass);

        if (!request.equals(checkData)) {
            throw new TalkException("数据解析不一致");
        }
    }
}
